package com.iseastar.guojiang.newcabinet.adapter;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.iseastar.dianxiaosan.model.Const;
import com.iseastar.guojiang.logic.AppLogic;
import com.iseastar.guojiang.model.ServiceTaskBackBean;
import com.iseastar.guojiang.model.ServiceTaskBean;
import com.shouhuobao.station.R;
import com.shouhuobao.take.utils.StringUtils;

import java.util.ArrayList;

import droid.frame.activity.base.BaseAdapterExt;
import droid.frame.utils.android.Log;
import droid.frame.utils.lang.Str;

/**
 * Created by joker on 2017/12/18.
 * 首页揽收任务适配器
 */
public class ServiceTaskAdapter extends BaseAdapterExt<ServiceTaskBean> {

    private final int NORMAL_TYPE = 0;//正常类型的数据
    private final int ASSOCIATE_TYPE = 1;//交接包裹的数据
    private final int SAME_CITY_TYPE = 2;//同城类型的数据

    private int normalNum = 0;
    private int sameCityNum = 0;
    private ServiceTaskBackBean serviceTaskBackBean = null;

    public ServiceTaskAdapter(ArrayList<ServiceTaskBean> items, Activity context) {
        super(items, context);
        setEmptyView(R.layout.service_task_layout_empty);
    }

    @Override
    public int getViewTypeCount() {
        if (hasEmptyView()) {
            return super.getViewTypeCount();
        } else {
            return 3;
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (hasEmptyView()) {
            return super.getItemViewType(position);
        } else {
            ServiceTaskBean bean = getItem(position);
            if (Const.CourierTaskStatus.sameCityTask == bean.getTaskType()) {
                return SAME_CITY_TYPE;
            } else if (Const.CourierTaskStatus.transferTask == bean.getTaskType()) {
                return ASSOCIATE_TYPE;
            } else {
                return NORMAL_TYPE;
            }
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (hasEmptyView()) {
            return super.getView(position, convertView, parent);
        }
        int type = getItemViewType(position);
        NormalViewHolder normalViewHolder = null;
        AssociateViewHolder associateViewHolder = null;
        SameCityViewHolder sameCityViewHolder = null;
        switch (type) {
            case NORMAL_TYPE:
                if (convertView == null || convertView.getTag() == null || !(convertView.getTag() instanceof NormalViewHolder)) {
                    normalViewHolder = new NormalViewHolder();
                    convertView = LayoutInflater.from(context).inflate(R.layout.layout_service_normal_item, parent, false);
                    normalViewHolder.normalTopBackgroundView = convertView.findViewById(R.id.normal_top_bg_view);
                    normalViewHolder.normalTopView = convertView.findViewById(R.id.normal_top_ll);
                    normalViewHolder.moneyLocationDescTV = (TextView) convertView.findViewById(R.id.money_location_desc_tv);
                    normalViewHolder.finishTaskDescTV = (TextView) convertView.findViewById(R.id.finish_task_desc_tv);
                    normalViewHolder.priceDescTV = (TextView) convertView.findViewById(R.id.price_desc_tv);
                    normalViewHolder.topLineView = convertView.findViewById(R.id.top_line);
                    normalViewHolder.parcelTypeTV = (TextView) convertView.findViewById(R.id.parcel_type_tv);
                    normalViewHolder.parcelTaskDescTV = (TextView) convertView.findViewById(R.id.parcel_task_desc_tv);
                    normalViewHolder.taskStatusDescTV = (TextView) convertView.findViewById(R.id.task_status_desc_tv);
                    normalViewHolder.parcelStepDescTV = (TextView) convertView.findViewById(R.id.parcel_step_desc_tv);
                    normalViewHolder.bootomLineView = convertView.findViewById(R.id.bootom_line);
                    normalViewHolder.buildNameTV = (TextView) convertView.findViewById(R.id.build_name_tv);
                    normalViewHolder.addressTV = (TextView) convertView.findViewById(R.id.address_tv);
                    normalViewHolder.timeTV = (TextView) convertView.findViewById(R.id.time_tv);
                    normalViewHolder.parcelRemarkTV = (TextView) convertView.findViewById(R.id.parcel_remark_tv);
                    normalViewHolder.bottomDivierLineView = convertView.findViewById(R.id.divier_line);
                    convertView.setTag(normalViewHolder);
                } else {
                    normalViewHolder = (NormalViewHolder) convertView.getTag();
                }
                break;
            case ASSOCIATE_TYPE:
                if (convertView == null || convertView.getTag() == null || !(convertView.getTag() instanceof AssociateViewHolder)) {
                    associateViewHolder = new AssociateViewHolder();
                    convertView = LayoutInflater.from(context).inflate(R.layout.layout_service_associate_item, parent, false);
                    associateViewHolder.topBackgroundView = convertView.findViewById(R.id.top_bg_view);
                    associateViewHolder.associateDescTV = (TextView) convertView.findViewById(R.id.associate_desc_tv);
                    associateViewHolder.associateTypeTV = (TextView) convertView.findViewById(R.id.associate_type_tv);
                    associateViewHolder.associateTaskDescTV = (TextView) convertView.findViewById(R.id.associate_task_desc_tv);
                    associateViewHolder.associateBuildNameTV = (TextView) convertView.findViewById(R.id.associate_build_name_tv);
                    associateViewHolder.associateAddressTV = (TextView) convertView.findViewById(R.id.associate_address_tv);
                    convertView.setTag(associateViewHolder);
                } else {
                    associateViewHolder = (AssociateViewHolder) convertView.getTag();
                }
                break;
            case SAME_CITY_TYPE:
                if (convertView == null || convertView.getTag() == null || !(convertView.getTag() instanceof SameCityViewHolder)) {
                    sameCityViewHolder = new SameCityViewHolder();
                    convertView = LayoutInflater.from(context).inflate(R.layout.layout_service_same_city_item, parent, false);
                    sameCityViewHolder.sameCityDetailTV = (TextView) convertView.findViewById(R.id.same_city_detail_tv);
                    sameCityViewHolder.takeBuildNameTV = (TextView) convertView.findViewById(R.id.take_build_name_tv);
                    sameCityViewHolder.takeAddressTV = (TextView) convertView.findViewById(R.id.take_address_tv);
                    sameCityViewHolder.sameCityStatusDescTV = (TextView) convertView.findViewById(R.id.same_city_status_desc_tv);
                    sameCityViewHolder.sendBuildNameTV = (TextView) convertView.findViewById(R.id.send_build_name_tv);
                    sameCityViewHolder.sendAddressTV = (TextView) convertView.findViewById(R.id.send_address_tv);
                    sameCityViewHolder.sendSomethingDescTV = (TextView) convertView.findViewById(R.id.send_something_desc_tv);
                    sameCityViewHolder.sendTimeTV = (TextView) convertView.findViewById(R.id.send_time_tv);
                    sameCityViewHolder.sendRemarkTV = (TextView) convertView.findViewById(R.id.send_remark_tv);
                    sameCityViewHolder.distanceTV = (TextView) convertView.findViewById(R.id.samecity_distance_tv);
                    convertView.setTag(sameCityViewHolder);
                } else {
                    sameCityViewHolder = (SameCityViewHolder) convertView.getTag();
                }
                break;
        }
        ServiceTaskBean bean = getItem(position);
        if (Const.CourierTaskStatus.visitTask == bean.getTaskType() || Const.CourierTaskStatus.stationTask == bean.getTaskType() || Const.CourierTaskStatus.cabinetTask == bean.getTaskType()) {
            normalViewHolder.parcelTaskDescTV.setText("￥" + bean.getTaskLucre() + "/" + Str.formatDoubleData(bean.getDistance() / 1000) + "km");
            normalViewHolder.buildNameTV.setText(bean.getBuildName());
            normalViewHolder.addressTV.setText(bean.getAddress());
        }
        if (Const.CourierTaskStatus.visitTask == bean.getTaskType()) {
            normalViewHolder.parcelTypeTV.setText("上门");
            normalViewHolder.parcelStepDescTV.setText("取");
            normalViewHolder.timeTV.setText(taskTimeStr(bean));
            if (StringUtils.isEmpty(bean.getRemark())) {
                normalViewHolder.parcelRemarkTV.setText("备注：无");
            } else {
                normalViewHolder.parcelRemarkTV.setText("备注：" + bean.getRemark());
            }
            setTaskStatusStr(normalViewHolder.taskStatusDescTV, bean);
        } else if (Const.CourierTaskStatus.stationTask == bean.getTaskType()) {
            normalViewHolder.parcelTypeTV.setText("驿站");
            normalViewHolder.parcelStepDescTV.setText("揽");
            normalViewHolder.timeTV.setText(taskTimeStr(bean));
            if (StringUtils.isEmpty(bean.getRemark())) {
                normalViewHolder.parcelRemarkTV.setText("备注：无");
            } else {
                normalViewHolder.parcelRemarkTV.setText("备注：" + bean.getRemark());
            }
            setTaskStatusStr(normalViewHolder.taskStatusDescTV, bean);
        } else if (Const.CourierTaskStatus.cabinetTask == bean.getTaskType()) {//到柜
            normalViewHolder.parcelTypeTV.setText("快递柜");
            normalViewHolder.parcelStepDescTV.setText("取");
            normalViewHolder.timeTV.setText(taskTimeStr(bean));
            if (StringUtils.isEmpty(bean.getRemark())) {
                normalViewHolder.parcelRemarkTV.setText("备注：无");
            } else {
                normalViewHolder.parcelRemarkTV.setText("备注：" + bean.getRemark());
            }
            setTaskStatusStr(normalViewHolder.taskStatusDescTV, bean);
        } else if (Const.CourierTaskStatus.transferTask == bean.getTaskType()) {//回仓
            associateViewHolder.associateTypeTV.setText("回仓");
            associateViewHolder.topBackgroundView.setVisibility(View.VISIBLE);
            associateViewHolder.associateDescTV.setText(bean.getBagCount() + "个包裹/" + Str.formatDoubleData(bean.getDistance() / 1000) + "km");
            associateViewHolder.associateBuildNameTV.setText(bean.getWareHouseName());
            associateViewHolder.associateAddressTV.setText(bean.getAddress());
        } else {
            sameCityViewHolder.sameCityDetailTV.setText("￥" + bean.getTaskLucre() + "/" + bean.getWeight() + "公斤/" + Str.formatDoubleData(bean.getDistance() / 1000) + "km");
            sameCityViewHolder.takeBuildNameTV.setText(bean.getBuildName());
            sameCityViewHolder.takeAddressTV.setText(bean.getAddress());
            sameCityViewHolder.sendBuildNameTV.setText(bean.getGiveBuildName());
            sameCityViewHolder.sendAddressTV.setText(bean.getGiveAddress());
            sameCityViewHolder.sendSomethingDescTV.setText("物品类型：" + bean.getCategory());
            sameCityViewHolder.sameCityStatusDescTV.setText(bean.getTaskStatusMessage());
            sameCityViewHolder.distanceTV.setText(Str.formatDoubleData(bean.getDistance1() / 1000) + "km");
            if (StringUtils.isEmpty(bean.getRemark())) {
                sameCityViewHolder.sendRemarkTV.setText("备注：无");
            } else {
                sameCityViewHolder.sendRemarkTV.setText("备注：" + bean.getRemark());
            }
            sameCityViewHolder.sendTimeTV.setText(taskTimeStr(bean));
        }
        //第一条数据显示同城，先判断同城,如果同城没有数据
        if (sameCityNum == 0) {
            handlerDoorStationData(type, normalViewHolder, position, sameCityNum);
        } else {//同城有数据
            handlerDoorStationData(type, normalViewHolder, position, sameCityNum);
        }
        if (normalNum == 0 && sameCityNum == 0 && type == ASSOCIATE_TYPE) {
            associateViewHolder.topBackgroundView.setVisibility(View.GONE);
        }
        return convertView;
    }

    private void handlerDoorStationData(int type, NormalViewHolder normalViewHolder, int position, int sameCityNum) {
        //如果上门，驿站和快递的数据多余两条，那么position为0的数据，不显示布局上面的虚线，normalNum-1位置的数据不现实下面的虚线
        //如果为一条数据，上门和下面的虚线都不显示
        if (type == NORMAL_TYPE) {
            if (sameCityNum == 0 || position >= sameCityNum + 1) {
                normalViewHolder.normalTopBackgroundView.setVisibility(View.GONE);
            }
            //如果上门，驿站，到柜的数据总和多余1条数据
            if (normalNum > 1) {
                normalViewHolder.topLineView.setVisibility(View.VISIBLE);
                normalViewHolder.normalTopView.setVisibility(View.GONE);
                normalViewHolder.bootomLineView.setVisibility(View.VISIBLE);
                normalViewHolder.bottomDivierLineView.setVisibility(View.VISIBLE);
                if (position == sameCityNum) {
                    normalViewHolder.topLineView.setVisibility(View.INVISIBLE);
                    normalViewHolder.normalTopView.setVisibility(View.VISIBLE);
                } else if (position == sameCityNum + normalNum - 1) {
                    normalViewHolder.bootomLineView.setVisibility(View.INVISIBLE);
                    normalViewHolder.bottomDivierLineView.setVisibility(View.INVISIBLE);
                }
            } else if (normalNum == 1) {//如果刚好有一条数据
                normalViewHolder.normalTopView.setVisibility(View.VISIBLE);
                normalViewHolder.topLineView.setVisibility(View.INVISIBLE);
                normalViewHolder.bootomLineView.setVisibility(View.INVISIBLE);
                normalViewHolder.bottomDivierLineView.setVisibility(View.INVISIBLE);
            }
            if (View.VISIBLE == normalViewHolder.normalTopView.getVisibility() && serviceTaskBackBean != null) {
                normalViewHolder.moneyLocationDescTV.setText(serviceTaskBackBean.getTakeTaskDesc());
                if (!StringUtils.isEmpty(serviceTaskBackBean.getTakeTaskProgressDesc())) {
                    normalViewHolder.finishTaskDescTV.setText("（" + serviceTaskBackBean.getTakeTaskProgressDesc() + "）");
                }
                normalViewHolder.priceDescTV.setText(serviceTaskBackBean.getTakeTaskCountDesc());
            }
        }
    }

    private class NormalViewHolder {
        View normalTopBackgroundView;//顶部占位
        View normalTopView;//顶部描述布局
        TextView moneyLocationDescTV;//价钱，任务地点描述  ￥15.9 /10个地点
        TextView finishTaskDescTV;//已完成任务描述
        TextView priceDescTV;//价钱计算描述
        View topLineView;//顶部线条
        TextView parcelTypeTV;//包裹类型描述
        TextView parcelTaskDescTV;//包裹详细描述，如 ￥3/1.5km
        TextView taskStatusDescTV;//每个包裹任务状态描述
        TextView parcelStepDescTV;//包裹步骤描述 上门显示取  驿站显示揽  柜子显示取
        View bootomLineView;//底部竖直线条
        TextView buildNameTV;//建筑物名字
        TextView addressTV;//地址名字
        TextView timeTV;//剩余时间
        TextView parcelRemarkTV;//备注描述
        View bottomDivierLineView;//底部分割线
    }

    private class AssociateViewHolder {
        View topBackgroundView;//顶部空白占位
        TextView associateDescTV;//交接描述  如 18个包裹/12km
        TextView associateTypeTV;//回仓
        TextView associateTaskDescTV;//交接任务描述提示
        TextView associateBuildNameTV;//交接建筑物名字
        TextView associateAddressTV;//交接的地址
    }

    private class SameCityViewHolder {
        TextView sameCityDetailTV;//同城价格，重要，距离的描述
        TextView takeBuildNameTV;//取货的建筑物名字
        TextView takeAddressTV;//取货的地址
        TextView sameCityStatusDescTV;//同城状态描述，进行中
        TextView sendBuildNameTV;//送往的建筑物名称
        TextView sendAddressTV;//送往的地址
        TextView sendSomethingDescTV;//物品描述
        TextView sendTimeTV;//剩余送达时间
        TextView sendRemarkTV;//同城备注
        TextView distanceTV;//同城距离
    }

    /**
     * 设置剩余时间
     *
     * @param bean
     * @return
     */
    private String taskTimeStr(ServiceTaskBean bean) {
        long overTime = bean.getOverTime();
        long startTime = bean.getCreateTime();
        Log.d("11111", System.currentTimeMillis());
        if (System.currentTimeMillis() > overTime) {
            return "已超时";
        } else {
            long time = overTime - startTime;
            String[] diffs = AppLogic.timeDiffStr(time);
            String timeText = "";
            if (diffs.length == 0) {
                timeText = "00小时00分";
            } else if (diffs.length == 1) {
                timeText = "00小时00分";
            } else if (diffs.length == 2) {
                timeText = "00小时" + diffs[0] + "分";
            } else if (diffs.length == 3) {
                timeText = diffs[0] + "小时" + diffs[1] + "分";
            }
            //            int sencondStart = timeText.indexOf("：");
            //            SpannableString secondSp = new SpannableString(timeText);
            //            secondSp.setSpan(new TextAppearanceSpan(getActivityContext(), R.style.passort_count_down_style), sencondStart + 1, timeText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            //            countDown.setText(secondSp, TextView.BufferType.SPANNABLE);
            return "剩余" + timeText;
        }
    }

    /**
     * 设置任务状态
     *
     * @param statusTV
     * @param bean
     */
    private void setTaskStatusStr(TextView statusTV, ServiceTaskBean bean) {
        if (Const.CourierTaskDoingStatus.TaskDoing == bean.getStatus()) {
            statusTV.setText("进行中");
        } else if (Const.CourierTaskDoingStatus.TaskFinished == bean.getStatus()) {
            statusTV.setText("已完成");
        } else if (Const.CourierTaskDoingStatus.TaskCancel == bean.getStatus()) {
            statusTV.setText("已取消");
        } else {
            statusTV.setText("未完成");
        }
    }

    /**
     * 设置完数据以后是否直接刷新
     *
     * @param items    参数为 null, 则清空adater的数据
     * @param isNotify
     */
    public void setItems(ArrayList<ServiceTaskBean> items, int sameCityNum, int normalNum, ServiceTaskBackBean serviceTaskBackBean, boolean isNotify) {
        this.sameCityNum = sameCityNum;
        this.normalNum = normalNum;
        this.serviceTaskBackBean = serviceTaskBackBean;
        if (items == null) {
            items = new ArrayList<ServiceTaskBean>();
        }
        this.items = items;
        if (this.MAX_SIZE != 0) {
            // 只取前MAX_SIZE个元素
            if (this.items.size() > MAX_SIZE) {
                this.items = (ArrayList<ServiceTaskBean>) this.items.subList(0, MAX_SIZE);
            }
        }
        if (isNotify) {
            notifyDataSetChanged();
        }
    }
}
